package com.xdy.secret.algorithm;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: XDY.
 * @Email: 2280944114@qq.com
 * @CreateTime: 2023-09-05  22:46
 * @Description: 消息摘要算法 MD5 SHA1 SHA256 SHA512
 * @Version: 1.0
 */
public class DigestDemo {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        //原文
        String input = "abc123";
        //摘要算法
        String algorithm = "MD5";
        System.out.println("MD5 ===> " + getDigest(input, algorithm));
        System.out.println("SHA1 ===> " + getDigest(input, "SHA-1"));
        System.out.println("SHA256 ===> " + getDigest(input, "SHA-256"));
        System.out.println("SHA512 ===> " + getDigest(input, "SHA-512"));
    }

    /**
     * 获取数字摘要
     *
     * @param input
     * @param algorithm
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String getDigest(String input, String algorithm) throws NoSuchAlgorithmException {
        //创建消息摘要对象
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        //得到加密后的
        byte[] bytes = digest.digest(input.getBytes());
        //使用base64进行转码
//            String encode = Base64.encode(bytes);
        //对密文进行迭代
        //	e99a18c428cb38d5f260853678922e03
        //  e99a18c428cb38d5f260853678922e03
        //  e99a18c428cb38d5f260853678922e3
        return toHex(bytes);
    }


    /**
     * 转换成16进制
     * @param bytes
     * @return
     */
    private static String toHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            //把密文转换成16进制
            String s = Integer.toHexString(b & 0xff);
            //如果密文长度是1，需要在高位补0
            sb.append(s.length() == 1 ? "0".concat(s) : s);
        }
        return sb.toString();
    }
}
